class Game {
    constructor() {
        this.canvas = document.getElementById('game-canvas');
        this.ctx = this.canvas.getContext('2d');
        this.resizeCanvas();

        // 细胞状态参数
        this.cell = {
            energy: 50,
            maxEnergy: 100,
            volume: 1,
            maxVolume: 5,
            membraneHealth: 100
        };

        // 细胞几何参数
        this.cellCenterX = this.canvas.width / 2;
        this.cellCenterY = this.canvas.height / 2;
        this.cellRadius = Math.min(this.canvas.width, this.canvas.height) * 0.4;

        // 物质粒子
        this.particles = [];
        this.externalParticles = []; // 细胞外部的物质
        this.maxParticles = 40;
        this.maxExternalParticles = 20;
        this.draggedParticle = null;
        this.dragOffset = { x: 0, y: 0 };

        // 收集统计
        this.collected = {
            rna: 0,
            amino: 0,
            energy: 0,
            lipid: 0,
            enzyme: 0,
            intermediate: 0
        };

        // 反应系统
        this.reactions = [];
        this.currentReaction = null;

        // 细胞框架结构
        this.cytoskeleton = [];
        this.createCytoskeleton();

        // 动画和交互
        this.animationId = null;
        this.isRunning = true;
        this.lastTime = 0;

        this.setupEventListeners();
        this.createInitialParticles();
        this.setupCellBoundary();
        this.startGameLoop();
    }

    resizeCanvas() {
        this.canvas.width = window.innerWidth;
        this.canvas.height = window.innerHeight;
    }

    setupEventListeners() {
        window.addEventListener('resize', () => {
            this.resizeCanvas();
            this.cellCenterX = this.canvas.width / 2;
            this.cellCenterY = this.canvas.height / 2;
            this.cellRadius = Math.min(this.canvas.width, this.canvas.height) * 0.4;
            this.setupCellBoundary();
        });

        // 鼠标事件
        this.canvas.addEventListener('mousedown', (e) => this.handleMouseDown(e));
        this.canvas.addEventListener('mousemove', (e) => this.handleMouseMove(e));
        this.canvas.addEventListener('mouseup', () => this.handleMouseUp());

        // 显示粒子信息
        document.getElementById('particle-info').style.display = 'block';
    }

    handleMouseDown(e) {
        const rect = this.canvas.getBoundingClientRect();
        const mouseX = e.clientX - rect.left;
        const mouseY = e.clientY - rect.top;

        // 首先检查内部粒子
        for (let particle of this.particles) {
            const dx = mouseX - particle.x;
            const dy = mouseY - particle.y;
            const distance = Math.sqrt(dx * dx + dy * dy);

            if (distance < particle.radius) {
                this.draggedParticle = particle;
                this.dragOffset.x = dx;
                this.dragOffset.y = dy;
                particle.isDragging = true;
                this.canvas.style.cursor = 'grabbing';
                return;
            }
        }

        // 然后检查外部粒子
        for (let particle of this.externalParticles) {
            const dx = mouseX - particle.x;
            const dy = mouseY - particle.y;
            const distance = Math.sqrt(dx * dx + dy * dy);

            if (distance < particle.radius) {
                this.draggedParticle = particle;
                this.dragOffset.x = dx;
                this.dragOffset.y = dy;
                particle.isDragging = true;
                this.canvas.style.cursor = 'grabbing';
                break;
            }
        }
    }

    handleMouseMove(e) {
        if (!this.draggedParticle) return;

        const rect = this.canvas.getBoundingClientRect();
        const mouseX = e.clientX - rect.left;
        const mouseY = e.clientY - rect.top;

        // 更新拖拽粒子的位置
        const newX = mouseX - this.dragOffset.x;
        const newY = mouseY - this.dragOffset.y;

        // 检查是否跨越细胞膜
        const wasInside = this.isInsideCell(this.draggedParticle.x, this.draggedParticle.y);
        const willBeInside = this.isInsideCell(newX, newY);

        // 细胞膜通透性：允许物质进出细胞
        if (wasInside !== willBeInside) {
            this.handleMembraneCrossing(this.draggedParticle, wasInside, willBeInside);
        }

        this.draggedParticle.x = newX;
        this.draggedParticle.y = newY;

        // 如果粒子在细胞内部，限制在细胞边界内
        if (willBeInside) {
            const dx = this.draggedParticle.x - this.cellCenterX;
            const dy = this.draggedParticle.y - this.cellCenterY;
            const distance = Math.sqrt(dx * dx + dy * dy);

            if (distance > this.cellRadius - this.draggedParticle.radius) {
                const angle = Math.atan2(dy, dx);
                this.draggedParticle.x = this.cellCenterX + Math.cos(angle) * (this.cellRadius - this.draggedParticle.radius);
                this.draggedParticle.y = this.cellCenterY + Math.sin(angle) * (this.cellRadius - this.draggedParticle.radius);
            }
        }

        this.checkReactions();
    }

    handleMembraneCrossing(particle, wasInside, willBeInside) {
        // 从细胞外部进入内部
        if (!wasInside && willBeInside) {
            // 从外部数组移动到内部数组
            if (particle.isExternal) {
                const index = this.externalParticles.indexOf(particle);
                if (index > -1) {
                    this.externalParticles.splice(index, 1);
                    particle.isExternal = false;
                    this.particles.push(particle);
                    this.collected[particle.type]++;
                    this.updateUI();
                }
            }
        }
        // 从细胞内部出去到外部
        else if (wasInside && !willBeInside) {
            // 从内部数组移动到外部数组
            if (!particle.isExternal) {
                const index = this.particles.indexOf(particle);
                if (index > -1) {
                    this.particles.splice(index, 1);
                    particle.isExternal = true;
                    this.externalParticles.push(particle);
                    this.collected[particle.type]--;
                    this.updateUI();

                    // 补充新的外部粒子
                    if (this.externalParticles.length < this.maxExternalParticles) {
                        this.createExternalParticle();
                    }
                }
            }
        }
    }

    handleMouseUp() {
        if (this.draggedParticle) {
            this.draggedParticle.isDragging = false;
            this.draggedParticle = null;
            this.canvas.style.cursor = 'default';
            this.hideReactionHint();
        }
    }

    createCytoskeleton() {
        // 创建细胞框架结构（由蛋白质纤维组成）
        const numFibers = 8;

        for (let i = 0; i < numFibers; i++) {
            const angle = (i / numFibers) * Math.PI * 2;
            const innerRadius = this.cellRadius * 0.3;
            const outerRadius = this.cellRadius * 0.7;

            // 创建放射状纤维
            const fiber = {
                startX: this.cellCenterX + Math.cos(angle) * innerRadius,
                startY: this.cellCenterY + Math.sin(angle) * innerRadius,
                endX: this.cellCenterX + Math.cos(angle) * outerRadius,
                endY: this.cellCenterY + Math.sin(angle) * outerRadius,
                thickness: 2,
                attachedParticles: [], // 可以附着粒子的位置
                type: 'radial'
            };

            this.cytoskeleton.push(fiber);
        }

        // 创建中央核糖体复合物（用于蛋白质合成）
        this.cytoskeleton.push({
            x: this.cellCenterX,
            y: this.cellCenterY,
            radius: 25,
            type: 'ribosome',
            attachedParticles: [],
            active: true
        });
    }

    createInitialParticles() {
        // 创建细胞内部粒子
        for (let i = 0; i < this.maxParticles; i++) {
            this.createParticle();
        }

        // 创建细胞外部粒子
        for (let i = 0; i < this.maxExternalParticles; i++) {
            this.createExternalParticle();
        }
    }

    createExternalParticle() {
        const types = ['rna', 'amino', 'energy', 'lipid', 'enzyme'];
        const type = types[Math.floor(Math.random() * types.length)];

        // 在细胞外部随机生成位置
        let x, y;
        do {
            x = Math.random() * this.canvas.width;
            y = Math.random() * this.canvas.height;
        } while (this.isInsideCell(x, y));

        const particle = {
            x: x,
            y: y,
            vx: (Math.random() - 0.5) * 0.3,
            vy: (Math.random() - 0.5) * 0.3,
            radius: Math.random() * 4 + 4,
            type: type,
            isDragging: false,
            value: Math.random() > 0.4 ? 1 : 0,
            id: Date.now() + Math.random(),
            lastCollision: 0,
            isExternal: true
        };

        this.externalParticles.push(particle);
    }

    isInsideCell(x, y) {
        const dx = x - this.cellCenterX;
        const dy = y - this.cellCenterY;
        const distance = Math.sqrt(dx * dx + dy * dy);
        return distance <= this.cellRadius;
    }

    createParticle() {
        const types = ['rna', 'amino', 'energy', 'lipid', 'enzyme', 'intermediate'];
        const type = types[Math.floor(Math.random() * types.length)];

        // 在细胞内部随机生成位置
        let x, y;
        do {
            const angle = Math.random() * Math.PI * 2;
            const distance = Math.random() * (this.cellRadius - 20);
            x = this.cellCenterX + Math.cos(angle) * distance;
            y = this.cellCenterY + Math.sin(angle) * distance;
        } while (this.checkParticleOverlap(x, y, 8));

        const particle = {
            x: x,
            y: y,
            vx: (Math.random() - 0.5) * 0.5,
            vy: (Math.random() - 0.5) * 0.5,
            radius: Math.random() * 6 + 6,
            type: type,
            isDragging: false,
            value: Math.random() > 0.3 ? 1 : 0,
            id: Date.now() + Math.random(),
            lastCollision: 0
        };

        this.particles.push(particle);
        this.collected[type]++;
        this.updateUI();
    }

    checkParticleOverlap(x, y, radius) {
        for (let particle of this.particles) {
            const dx = x - particle.x;
            const dy = y - particle.y;
            const distance = Math.sqrt(dx * dx + dy * dy);
            if (distance < radius + particle.radius) {
                return true;
            }
        }
        return false;
    }

    setupCellBoundary() {
        const boundary = document.getElementById('cell-boundary');
        boundary.style.width = this.cellRadius * 2 + 'px';
        boundary.style.height = this.cellRadius * 2 + 'px';
        boundary.style.left = (this.cellCenterX - this.cellRadius) + 'px';
        boundary.style.top = (this.cellCenterY - this.cellRadius) + 'px';
    }

    checkReactions() {
        if (!this.draggedParticle) return;

        const nearbyParticles = this.findNearbyParticles(this.draggedParticle, 50);

        const reaction = this.checkPossibleReaction(this.draggedParticle, nearbyParticles);

        if (reaction) {
            this.showReactionHint(reaction);
        } else {
            this.hideReactionHint();
        }
    }

    findNearbyParticles(centerParticle, radius) {
        const nearby = [];
        for (let particle of this.particles) {
            if (particle === centerParticle) continue;

            const dx = particle.x - centerParticle.x;
            const dy = particle.y - centerParticle.y;
            const distance = Math.sqrt(dx * dx + dy * dy);

            if (distance <= radius) {
                nearby.push({ particle, distance });
            }
        }
        return nearby;
    }

    checkPossibleReaction(draggedParticle, nearbyParticles) {
        // 蛋白质合成：RNA + 酶 + 氨基酸
        if (draggedParticle.type === 'rna') {
            const hasEnzyme = nearbyParticles.some(p => p.particle.type === 'enzyme');
            const hasAmino = nearbyParticles.some(p => p.particle.type === 'amino');
            if (hasEnzyme && hasAmino) {
                return {
                    type: 'protein_synthesis',
                    description: '蛋白质合成反应',
                    reactants: ['rna', 'enzyme', 'amino'],
                    product: 'protein'
                };
            }
        }

        // 能量转换：能量 + 酶
        if (draggedParticle.type === 'energy') {
            const hasEnzyme = nearbyParticles.some(p => p.particle.type === 'enzyme');
            if (hasEnzyme) {
                return {
                    type: 'energy_conversion',
                    description: '能量转换反应',
                    reactants: ['energy', 'enzyme'],
                    product: 'atp'
                };
            }
        }

        // RNA复制：RNA + 酶
        if (draggedParticle.type === 'rna') {
            const hasEnzyme = nearbyParticles.some(p => p.particle.type === 'enzyme');
            if (hasEnzyme && nearbyParticles.length >= 2) {
                return {
                    type: 'rna_replication',
                    description: 'RNA复制反应',
                    reactants: ['rna', 'enzyme'],
                    product: 'new_rna'
                };
            }
        }

        return null;
    }

    showReactionHint(reaction) {
        const hint = document.getElementById('reaction-hint');
        const text = document.getElementById('reaction-text');

        text.textContent = reaction.description;
        hint.style.display = 'block';
        hint.style.left = this.draggedParticle.x + 20 + 'px';
        hint.style.top = this.draggedParticle.y - 30 + 'px';
    }

    hideReactionHint() {
        document.getElementById('reaction-hint').style.display = 'none';
    }

    updateParticles(deltaTime) {
        // 更新内部粒子
        this.particles.forEach((particle, index) => {
            if (particle.isDragging) return;

            // 应用扩散运动
            particle.x += particle.vx * deltaTime * 0.1;
            particle.y += particle.vy * deltaTime * 0.1;

            // 细胞内部边界碰撞
            const dx = particle.x - this.cellCenterX;
            const dy = particle.y - this.cellCenterY;
            const distance = Math.sqrt(dx * dx + dy * dy);

            if (distance > this.cellRadius - particle.radius) {
                const angle = Math.atan2(dy, dx);
                particle.x = this.cellCenterX + Math.cos(angle) * (this.cellRadius - particle.radius);
                particle.y = this.cellCenterY + Math.sin(angle) * (this.cellRadius - particle.radius);

                // 反弹
                particle.vx *= -0.5;
                particle.vy *= -0.5;
            }

            // 酶吸附效果
            this.applyEnzymeAttraction(particle);

            // 粒子间碰撞
            this.handleParticleCollisions(particle, index, this.particles);

            // 添加随机扰动
            particle.vx += (Math.random() - 0.5) * 0.01;
            particle.vy += (Math.random() - 0.5) * 0.01;

            // 限制速度
            const speed = Math.sqrt(particle.vx * particle.vx + particle.vy * particle.vy);
            if (speed > 1) {
                particle.vx = (particle.vx / speed) * 1;
                particle.vy = (particle.vy / speed) * 1;
            }
        });

        // 更新外部粒子
        this.externalParticles.forEach((particle, index) => {
            if (particle.isDragging) return;

            // 外部粒子移动更慢
            particle.x += particle.vx * deltaTime * 0.05;
            particle.y += particle.vy * deltaTime * 0.05;

            // 屏幕边界碰撞
            if (particle.x <= particle.radius || particle.x >= this.canvas.width - particle.radius) {
                particle.vx *= -1;
                particle.x = Math.max(particle.radius, Math.min(this.canvas.width - particle.radius, particle.x));
            }
            if (particle.y <= particle.radius || particle.y >= this.canvas.height - particle.radius) {
                particle.vy *= -1;
                particle.y = Math.max(particle.radius, Math.min(this.canvas.height - particle.radius, particle.y));
            }

            // 酶吸附效果（外部粒子也可以被吸附）
            this.applyEnzymeAttraction(particle);

            // 外部粒子间的轻微碰撞
            this.handleParticleCollisions(particle, index, this.externalParticles);

            // 添加随机扰动
            particle.vx += (Math.random() - 0.5) * 0.005;
            particle.vy += (Math.random() - 0.5) * 0.005;

            // 限制速度
            const speed = Math.sqrt(particle.vx * particle.vx + particle.vy * particle.vy);
            if (speed > 0.5) {
                particle.vx = (particle.vx / speed) * 0.5;
                particle.vy = (particle.vy / speed) * 0.5;
            }
        });
    }

    handleParticleCollisions(particle, index, particleArray) {
        for (let i = index + 1; i < particleArray.length; i++) {
            const other = particleArray[i];
            if (other.isDragging) continue;

            const dx = other.x - particle.x;
            const dy = other.y - particle.y;
            const distance = Math.sqrt(dx * dx + dy * dy);
            const minDistance = particle.radius + other.radius;

            if (distance < minDistance) {
                // 分离粒子
                const overlap = minDistance - distance;
                const separationX = (dx / distance) * overlap * 0.5;
                const separationY = (dy / distance) * overlap * 0.5;

                particle.x -= separationX;
                particle.y -= separationY;
                other.x += separationX;
                other.y += separationY;

                // 交换速度（弹性碰撞）
                const tempVx = particle.vx;
                const tempVy = particle.vy;
                particle.vx = other.vx * 0.8;
                particle.vy = other.vy * 0.8;
                other.vx = tempVx * 0.8;
                other.vy = tempVy * 0.8;
            }
        }
    }

    applyEnzymeAttraction(particle) {
        // 酶不会被吸附，只会吸附其他物质
        if (particle.type === 'enzyme') return;

        // 查找附近的酶
        this.particles.forEach(enzyme => {
            if (enzyme.type !== 'enzyme') return;

            const dx = enzyme.x - particle.x;
            const dy = enzyme.y - particle.y;
            const distance = Math.sqrt(dx * dx + dy * dy);

            // 吸附范围（酶半径的3倍）
            const attractionRange = enzyme.radius * 3;

            if (distance < attractionRange && distance > enzyme.radius + particle.radius) {
                // 计算吸引力（随距离减弱）
                const force = 0.002 * (1 - distance / attractionRange);
                const forceX = (dx / distance) * force;
                const forceY = (dy / distance) * force;

                // 施加吸引力
                particle.vx += forceX;
                particle.vy += forceY;
            }
        });
    }

    drawBackground() {
        // 细胞内部背景 - 半透明的细胞质
        const gradient = this.ctx.createRadialGradient(
            this.cellCenterX, this.cellCenterY, 0,
            this.cellCenterX, this.cellCenterY, this.cellRadius
        );
        gradient.addColorStop(0, 'rgba(173, 216, 230, 0.1)');
        gradient.addColorStop(0.7, 'rgba(173, 216, 230, 0.05)');
        gradient.addColorStop(1, 'rgba(173, 216, 230, 0.01)');

        this.ctx.fillStyle = gradient;
        this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);

        // 绘制细胞框架
        this.drawCytoskeleton();

        // 细胞膜轮廓
        this.ctx.save();
        this.ctx.strokeStyle = 'rgba(255, 255, 255, 0.2)';
        this.ctx.lineWidth = 2;
        this.ctx.beginPath();
        this.ctx.arc(this.cellCenterX, this.cellCenterY, this.cellRadius, 0, Math.PI * 2);
        this.ctx.stroke();
        this.ctx.restore();

        // 添加细胞内部的微小颗粒流动效果
        for (let i = 0; i < 30; i++) {
            const angle = Math.random() * Math.PI * 2;
            const distance = Math.random() * this.cellRadius * 0.8;
            const x = this.cellCenterX + Math.cos(angle) * distance;
            const y = this.cellCenterY + Math.sin(angle) * distance;

            this.ctx.beginPath();
            this.ctx.arc(x, y, Math.random() * 2 + 1, 0, Math.PI * 2);
            this.ctx.fillStyle = 'rgba(255, 255, 255, 0.1)';
            this.ctx.fill();
        }
    }

    drawCytoskeleton() {
        this.cytoskeleton.forEach(structure => {
            this.ctx.save();

            if (structure.type === 'radial') {
                // 绘制放射状纤维
                this.ctx.strokeStyle = 'rgba(100, 149, 237, 0.4)';
                this.ctx.lineWidth = structure.thickness;
                this.ctx.beginPath();
                this.ctx.moveTo(structure.startX, structure.startY);
                this.ctx.lineTo(structure.endX, structure.endY);
                this.ctx.stroke();

                // 在纤维上添加一些节点
                const numNodes = 3;
                for (let i = 0; i < numNodes; i++) {
                    const t = (i + 1) / (numNodes + 1);
                    const nodeX = structure.startX + (structure.endX - structure.startX) * t;
                    const nodeY = structure.startY + (structure.endY - structure.startY) * t;

                    this.ctx.beginPath();
                    this.ctx.arc(nodeX, nodeY, 3, 0, Math.PI * 2);
                    this.ctx.fillStyle = 'rgba(100, 149, 237, 0.6)';
                    this.ctx.fill();
                }
            } else if (structure.type === 'ribosome') {
                // 绘制中央核糖体复合物
                this.ctx.strokeStyle = 'rgba(255, 165, 0, 0.6)';
                this.ctx.lineWidth = 3;
                this.ctx.beginPath();
                this.ctx.arc(structure.x, structure.y, structure.radius, 0, Math.PI * 2);
                this.ctx.stroke();

                // 核糖体内部结构
                this.ctx.strokeStyle = 'rgba(255, 165, 0, 0.4)';
                this.ctx.lineWidth = 1;
                for (let i = 0; i < 6; i++) {
                    const angle = (i / 6) * Math.PI * 2;
                    const innerRadius = structure.radius * 0.6;
                    const outerRadius = structure.radius * 0.9;

                    this.ctx.beginPath();
                    this.ctx.moveTo(
                        structure.x + Math.cos(angle) * innerRadius,
                        structure.y + Math.sin(angle) * innerRadius
                    );
                    this.ctx.lineTo(
                        structure.x + Math.cos(angle) * outerRadius,
                        structure.y + Math.sin(angle) * outerRadius
                    );
                    this.ctx.stroke();
                }

                // 中央活性区域
                this.ctx.beginPath();
                this.ctx.arc(structure.x, structure.y, structure.radius * 0.3, 0, Math.PI * 2);
                this.ctx.fillStyle = structure.active ? 'rgba(255, 165, 0, 0.8)' : 'rgba(128, 128, 128, 0.5)';
                this.ctx.fill();
            }

            this.ctx.restore();
        });
    }

    drawParticles() {
        // 绘制外部粒子（细胞外部环境中的物质）
        this.externalParticles.forEach(particle => {
            this.drawSingleParticle(particle);
        });

        // 绘制内部粒子（细胞内部的物质）
        this.particles.forEach(particle => {
            this.drawSingleParticle(particle);
        });
    }

    drawSingleParticle(particle) {
        this.ctx.save();

        // 根据类型设置颜色和外观
        let color, emoji;
        switch (particle.type) {
            case 'rna':
                color = '#007bff';
                emoji = '🔵';
                break;
            case 'amino':
                color = '#28a745';
                emoji = '🟢';
                break;
            case 'energy':
                color = '#ffc107';
                emoji = '🟡';
                break;
            case 'lipid':
                color = '#6c757d';
                emoji = '⚪';
                break;
            case 'enzyme':
                color = '#dc3545';
                emoji = '🔴';
                break;
            case 'intermediate':
                color = '#8b45c3';
                emoji = '🟣';
                break;
            default:
                color = '#fff';
                emoji = '⚪';
        }

        // 拖拽状态高亮
        if (particle.isDragging) {
            this.ctx.shadowColor = color;
            this.ctx.shadowBlur = 15;
        }

        // 外部粒子使用半透明效果
        if (particle.isExternal) {
            this.ctx.globalAlpha = 0.7;
        }

        // 粒子主体
        this.ctx.beginPath();
        this.ctx.arc(particle.x, particle.y, particle.radius, 0, Math.PI * 2);
        this.ctx.fillStyle = color;
        this.ctx.fill();

        // 粒子边框
        this.ctx.beginPath();
        this.ctx.arc(particle.x, particle.y, particle.radius, 0, Math.PI * 2);
        this.ctx.strokeStyle = particle.isDragging ? '#fff' : 'rgba(255, 255, 255, 0.3)';
        this.ctx.lineWidth = particle.isDragging ? 2 : 1;
        this.ctx.stroke();

        // 有效性指示器（白色小点表示有效）
        if (particle.value > 0) {
            this.ctx.beginPath();
            this.ctx.arc(particle.x + particle.radius * 0.6, particle.y - particle.radius * 0.6, particle.radius * 0.2, 0, Math.PI * 2);
            this.ctx.fillStyle = 'rgba(255, 255, 255, 0.9)';
            this.ctx.fill();
        }

        this.ctx.restore();

        // 显示粒子类型标识（小图标）
        if (!particle.isDragging) {
            this.ctx.fillStyle = particle.isExternal ? 'rgba(255, 255, 255, 0.5)' : '#fff';
            this.ctx.font = '8px Arial';
            this.ctx.textAlign = 'center';
            this.ctx.fillText(emoji, particle.x, particle.y + particle.radius * 0.3);
        }
    }

    updateUI() {
        // 更新能量条
        const energyPercent = (this.cell.energy / this.cell.maxEnergy) * 100;
        document.getElementById('energy-fill').style.width = energyPercent + '%';

        // 更新体积条
        const volumePercent = (this.cell.volume / this.cell.maxVolume) * 100;
        document.getElementById('volume-fill').style.width = volumePercent + '%';

        // 更新统计（显示内部物质数量）
        document.getElementById('stats').textContent =
            `内部 - RNA: ${this.collected.rna} | 氨基酸: ${this.collected.amino} | 能量: ${this.collected.energy} | 酶: ${this.collected.enzyme}`;

        // 能量消耗
        if (this.cell.energy <= 0) {
            this.gameOver();
        }
    }

    gameOver() {
        this.isRunning = false;
        const externalCount = this.externalParticles.length;
        alert('细胞能量耗尽！游戏结束。\n\n细胞内部物质统计：\n' +
              'RNA: ' + this.collected.rna +
              '\n氨基酸: ' + this.collected.amino +
              '\n能量物质: ' + this.collected.energy +
              '\n脂质: ' + this.collected.lipid +
              '\n酶: ' + this.collected.enzyme +
              '\n中间产物: ' + this.collected.intermediate +
              '\n\n细胞外部物质数量: ' + externalCount);
        location.reload();
    }

    checkOngoingReactions() {
        // 检查是否有粒子足够接近来触发反应
        for (let i = 0; i < this.particles.length; i++) {
            const particle1 = this.particles[i];
            if (particle1.isDragging) continue;

            for (let j = i + 1; j < this.particles.length; j++) {
                const particle2 = this.particles[j];
                if (particle2.isDragging) continue;

                const dx = particle2.x - particle1.x;
                const dy = particle2.y - particle1.y;
                const distance = Math.sqrt(dx * dx + dy * dy);

                if (distance < particle1.radius + particle2.radius + 10) {
                    const nearbyParticles = [{particle: particle2, distance: distance}];
                    const reaction = this.checkPossibleReaction(particle1, nearbyParticles);
                    if (reaction) {
                        this.triggerReaction(reaction, [particle1, particle2]);
                        return; // 一次只触发一个反应
                    }
                }
            }
        }
    }

    triggerReaction(reaction, reactants) {
        // 显示反应进度
        this.showReactionProgress(reaction);

        // 模拟反应时间
        setTimeout(() => {
            this.completeReaction(reaction, reactants);
        }, 2000);
    }

    showReactionProgress(reaction) {
        const progressDiv = document.getElementById('reaction-progress');
        const textDiv = document.getElementById('progress-text');
        const fillDiv = document.getElementById('progress-fill');

        textDiv.textContent = reaction.description + '进行中...';
        fillDiv.style.width = '0%';
        progressDiv.style.display = 'block';

        // 动画进度条
        let progress = 0;
        const animate = () => {
            progress += 2;
            fillDiv.style.width = progress + '%';

            if (progress < 100) {
                requestAnimationFrame(animate);
            }
        };
        animate();

        // 2秒后隐藏
        setTimeout(() => {
            progressDiv.style.display = 'none';
        }, 2000);
    }

    completeReaction(reaction, reactants) {
        // 移除反应物
        reactants.forEach(particle => {
            const index = this.particles.indexOf(particle);
            if (index > -1) {
                this.particles.splice(index, 1);
                this.collected[particle.type]--;
            }
        });

        // 生成产物
        this.createReactionProduct(reaction, reactants);

        this.updateUI();
    }

    createReactionProduct(reaction, reactants) {
        let productType;
        switch (reaction.type) {
            case 'protein_synthesis':
                productType = 'intermediate'; // 蛋白质
                break;
            case 'energy_conversion':
                productType = 'energy'; // ATP
                break;
            case 'rna_replication':
                productType = 'rna'; // 新RNA
                break;
            default:
                productType = 'intermediate';
        }

        // 在反应位置附近创建产物
        const centerX = reactants.reduce((sum, p) => sum + p.x, 0) / reactants.length;
        const centerY = reactants.reduce((sum, p) => sum + p.y, 0) / reactants.length;

        const product = {
            x: centerX + (Math.random() - 0.5) * 20,
            y: centerY + (Math.random() - 0.5) * 20,
            vx: (Math.random() - 0.5) * 0.5,
            vy: (Math.random() - 0.5) * 0.5,
            radius: Math.random() * 4 + 8,
            type: productType,
            isDragging: false,
            value: 1,
            id: Date.now() + Math.random(),
            lastCollision: 0
        };

        // 确保产物在细胞内部
        const dx = product.x - this.cellCenterX;
        const dy = product.y - this.cellCenterY;
        const distance = Math.sqrt(dx * dx + dy * dy);

        if (distance > this.cellRadius - product.radius) {
            const angle = Math.atan2(dy, dx);
            product.x = this.cellCenterX + Math.cos(angle) * (this.cellRadius - product.radius);
            product.y = this.cellCenterY + Math.sin(angle) * (this.cellRadius - product.radius);
        }

        this.particles.push(product);
        this.collected[productType]++;
    }

    gameLoop(currentTime = 0) {
        if (!this.isRunning) return;

        const deltaTime = currentTime - this.lastTime;
        this.lastTime = currentTime;

        // 清除画布
        this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);

        // 绘制背景
        this.drawBackground();

        // 更新和绘制粒子
        if (deltaTime < 100) { // 防止时间跳跃
            this.updateParticles(deltaTime);
        }
        this.drawParticles();

        // 绘制细胞结构
        // this.drawCell(); // 如果需要可以添加

        // 每秒检查一次反应
        if (Math.random() < 0.016) { // ~1次/秒
            this.checkOngoingReactions();
        }

        this.animationId = requestAnimationFrame((time) => this.gameLoop(time));
    }

    startGameLoop() {
        this.gameLoop();
    }
}

// 启动游戏
window.addEventListener('load', () => {
    new Game();
});
